﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace AMMVVMLibrary.Portable
{
    public abstract class ViewModelBase : INotifyPropertyChanged
    {
        public DelegateCommand GoBackCommand { get; set; }

        public ViewModelBase(INavigationService navigationService)
        {
            NavigationService = navigationService;
            GoBackCommand = new DelegateCommand(
                () => { NavigationService.GoBack(); },
                () => { return NavigationService.CanGoBack; }
                );
        }

        public ViewModelBase()
        {
            GoBackCommand = new DelegateCommand(
                () => { NavigationService.GoBack(); },
                () => { return NavigationService.CanGoBack; }
                );
        }

        public abstract void LoadData(object parameter);

        /// <summary>
        /// Reference to the concrete navigation service
        /// </summary>
        public static INavigationService NavigationService { get; set; }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        public void OnPropertyChanged(String propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));

        }

        public void OnPropertyChanged<TProperty>(Expression<Func<TProperty>> property)
        {
            var lambda = (LambdaExpression)property;
            MemberExpression memberExpression;

            if (lambda.Body is UnaryExpression)
            {
                var unaryExpression = (UnaryExpression)lambda.Body;
                memberExpression = (MemberExpression)unaryExpression.Operand;
            }
            else
            {
                memberExpression = (MemberExpression)lambda.Body;
            }
            OnPropertyChanged(memberExpression.Member.Name);
        }
    }
}
